<?php
/**
 * Created by PhpStorm.
 * @User: 王海东
 * @Date: 2018/9/7 15:52
 */

namespace app\api\controller;

use app\common\controller\BaseController;
use app\common\model\Admin;
use app\common\model\Bankinfo;
use app\common\model\Capital;
use app\common\model\Common;
use app\common\model\Config;
use app\common\model\User;
use app\common\model\UserHierarchy;
use app\common\model\UserReal;
use app\common\model\UserToken;
use think\Db;
use think\facade\Cookie;
use think\facade\Session;

class UserController extends BaseController
{

    /**
     * 获取注册方式
     * @author 王崇全
     * @date   2019/1/7 11:53
     * @return void ["reg_type" => 注册方式,//1 手机号;2,邮箱]
     */
    public function getRegType()
    {

        //注册方式
        $c       = new Config();
        $regType = $c->get('reg_method');

        rjd(["reg_type" => $regType]);

    }

    /**
     * 用户注册
     * （4位邀请码为用户推广 6位邀请码为管理员推广）
     * @author 王海东
     * @date
     * @return void
     * @throws \Exception
     */
    public function register()
    {
        $phoneEmail = Session::get("phone_email");
        if (!$phoneEmail) {
            rj(1, "请先发送验证码");
        }

        //发送验证码是保存下的手机号或邮件
        $c       = new Config();
        $regType = $c->get('reg_method');

        if ($regType == 1) { //手机号
            $phone    = $phoneEmail;
            $userName = $phone;
        } else {
            $email    = $phoneEmail;
            $userName = $email;
            $userName = explode("@", $userName);
            $userName = reset($userName);
        }

        $in = $this->I([
            [
                "captcha|验证码",
                null,
                "s",
                "require",
            ],
            [
                "password|密码",
                null,
                "s",
                "require|alphaDash|length:8,40",
            ],
            [
                "user_name|用户名",
                $userName,
                "s",
                "max:25",
            ],
            [
                "inviting_code|邀请码",
                null,
                "s",
            ],
        ]);

        $common = new Common();
        //检测验证码
        if (!$common->checkCaptcha($in['captcha'])) {
            rj(1, '验证码错误!');
        }

        //注册方式
        $c       = new Config();
        $regType = $c->get('reg_method');


        $user = new User();
        $c    = new Common();
        if ($regType == 1) { //手机号
            //检测手机号是否存在
            if ($user->checkExits(2, $phoneEmail)) {
                rj(1, '注册手机号已存在!');
            }

        } else { //邮箱
            //检测邮箱是否存在
            if ($user->checkExits(3, $in['email'])) {
                rj(1, '注册邮箱已存在！');
            }
        }

        //检测邀请码
        $admin_id    = null;
        $inviting_id = null;

        $user = new User();

        $in['inviting_code'] = trim($in['inviting_code']);
        if (strlen($in['inviting_code']) == 4) { //用户推广
            $inviting = $user->getUserByCode($in['inviting_code']);
            if (!$inviting) {
                rj(1, '无效的邀请码');
            }

            $admin_id    = $inviting['admin_id'];
            $inviting_id = $inviting['hierarchy_id'];

        } elseif (strlen($in['inviting_code']) == 6) { //管理员推广
            $a      = new Admin();
            $adm_id = $a->getIdByCode($in['inviting_code']);
            if (!$adm_id) {
                rj(1, '无效的邀请码');
            }

            $admin_id = $adm_id;
        } else { //无推广
            $admin_id    = '';
            $inviting_id = '';
        }

        $data = [
            'nick_name' => $in['user_name'],
            'name'      => $in['user_name'],
            'tel'       => $phone ?? '',
            'email'     => $email ?? '',
            'available' => 'yes',
            'code'      => create_invite_code(4),
            'admin_id'  => $admin_id ?? 1,
        ];

        $c  = new Capital();
        $uh = new UserHierarchy();

        Db::startTrans();
        try {

            //用户层级
            $hierarchy_id = $uh->addHierarchy($inviting_id);

            $data['hierarchy_id'] = $hierarchy_id;

            //账户添加
            $id = $user->add($in['user_name'], $in['password'], $data);

            //资金账户
            $c->add($id);

        } catch (\Exception $e) {
            Db::rollback();

            rj(1, $e->getMessage());
        }

        Db::commit();
        rj();
    }

    /**
     * 用户登录
     * @author 王海东
     * @date
     * @return void
     * @throws \Exception
     */
    public function login()
    {
        $in = $this->I([
            [
                "username|手机号或邮箱",
                null,
                "s",
                "require",
            ],
            [
                "password|密码",
                null,
                "s",
                "require",
            ],
        ]);

        $u = new User();

        $data = $u->checkPwd($in['username'], $in['password']);
        if (!$data) {
            rj(1, '用户名或密码输入错误');
        }

        $info = $u->getInfo($in['username']);
        if ($info['available'] == 'no') {
            rj(1, '该账户被禁用');
        }

        //获取token
        $token = '';
        try {
            $userToken = new UserToken();
            $token     = $userToken->insertToken($info['id']);

            Cookie::set("token", $token);
        } catch (\Exception $e) {
        }

        rjd(['token' => $token]);
    }

    /**
     * 重置密码
     * @author 王海东
     * @date
     * @return void
     * @throws \Exception
     */
    public function rePwd()
    {
        $phoneEmail = Session::get("phone_email");
        if (!$phoneEmail) {
            rj(1, "请先发送验证码");
        }

        $in = $this->I([
            [
                "password|密码",
                null,
                "s",
                "require|max:25",
            ],
            [
                "code|验证码",
                null,
                "s",
                "require",
            ],
        ]);

        //验证码
        $common = new Common();
        if (!$common->checkCaptcha($in['code'])) {
            rj(1, '验证码错误!');
        }

        //查询用户名是否存在
        $user = new User();
        $info = $user->getInfo($phoneEmail);
        if (!$info) {
            rj(1, '该用户不存在!');
        }

        if (!$user->edit($info['id'], ['pwd' => $in['password']])) {
            rj(1, '密码修改失败');
        }

        rj();
    }

    /**
     * 修改登录密码
     * @author 王海东
     * @date
     * @return void
     * @throws \Exception
     */
    public function reLoginPwd()
    {
        $in = $this->I([
            [
                "oldPwd|原密码",
                null,
                "s",
                "require",
            ],
            [
                "newPwd|新密码",
                null,
                "s",
                "require|alphaDash|length:8,40",
            ],
        ]);

        $u   = new User();
        $res = $u->checkPwdById(UID, $in['oldPwd']);
        if (!$res) {
            rj(1, '原密码输入错误');
        }

        if (!$u->edit(UID, ['pwd' => $in['newPwd']])) {
            rj(1, '修改失败');
        }

        rj();
    }

    /**
     * 查询用户详细信息
     * @author 王海东
     * @date
     * @return void
     * @throws \Exception
     */
    public function getInfo()
    {
        if (is_null(UID)) {
            rj(2, '登录失效，请重新登录');
        }

        $u    = new User();
        $data = $u->info(UID);
        if (!$data) {
            rj(1, '用户不存在');
        }

        //删除密码
        unset($data["pwd"]);

        rjd($data);
    }

    /**
     * 更改手机号
     * @author 王海东
     * @date
     * @return void
     * @throws \Exception
     */
    public function bindPhone()
    {
        $phone = Session::get("phone_email");
        if (!$phone) {
            rj(1, "请先发送验证码");
        }

        if (is_null(UID)) {
            rj(2, '登录失效，请重新登录!');
        }

        $in = $this->I([
            [
                "code|短信验证码",
                null,
                "s",
                "require|max:6",
            ],
        ]);

        $common = new Common();
        if (!$common->checkCaptcha($in['code'])) {
            rj(1, '验证码错误!');
        }

        $u = new User();
        if ($u->checkExits(2, $phone)) {
            rj(1, '手机号已绑定，请不要重复绑定');
        }

        if (!$u->edit(UID, ['tel' => $phone])) {
            rj(1, '修改失败');
        }

        rj();
    }

    /**
     * 更改邮箱
     * @author 王崇全
     * @date
     * @return void
     * @throws \Exception
     */
    public function bindEmail()
    {
        $email = Session::get("phone_email");
        if (!$email) {
            rj(1, "请先发送验证码");
        }

        if (is_null(UID)) {
            rj(2, '登录失效，请重新登录!');
        }

        $in = $this->I([
            [
                "code|邮件验证码",
                null,
                "s",
                "require|max:6",
            ],
        ]);

        $common = new Common();
        if (!$common->checkCaptcha($in['code'])) {
            rj(1, '验证码错误!');
        }

        $u = new User();
        if ($u->checkExits(3, $email)) {
            rj(1, '此邮箱已绑定，请不要重复绑定');
        }

        if (!$u->edit(UID, ['email' => $email])) {
            rj(1, '修改失败');
        }

        rj();
    }

    /**
     * 绑定银行卡
     * @author 王海东
     * @date
     * @return void
     * @throws \Exception
     */
    public function bindBank()
    {
        if (is_null(UID)) {
            rj(2, '登录失效，请重新登录');
        }

        $in = $this->I([
            [
                "bankname|银行名称",
                null,
                "s",
                "require",
            ],
            [
                "bank_card_num|银行卡号",
                null,
                "d",
                "require",
            ],
            [
                "bank_branch|支行名称",
                null,
                "s",
                "require",
            ],
            [
                "busername|持卡人姓名",
                null,
                "s",
                "require",
            ],
            [
                "card|身份证号",
                null,
                "s",
                "require|idCard",
            ],
            [
                "mobile|银行预留手机号",
                null,
                "s",
                "require|mobile",
            ],
            [
                "area|开户区代码",
                null,
                "d",
                "require",
            ],
        ]);

        $b = new Bankinfo();

        if ($b->checkExits(2, $in['bank_card_num'])) {
            rj(1, '此银行卡已绑定，请勿重复绑定');
        }

        $ret = $b->add(UID, $in);
        if (!$ret) {
            rj(1, '绑定失败');
        }

        rj();
    }

    /**
     * 查询用户绑定银行卡
     * @author 王海东
     * @date
     * @return void
     * @throws \Exception
     */
    public function selectBank()
    {
        if (is_null(UID)) {
            rj(2, '登录失效，请重新登录');
        }

        $in = $this->I([
            [
                "page|页码",
                DEF_PAGE_NO,
                "d",
            ],
            [
                "pageSize|页幅",
                DEF_PAGE_SIZE,
                "d",
            ],
        ]);

        $b = new Bankinfo();

        $data = $b->userList(UID, $in['page'], $in['pageSize']);

        rjd($data);
    }

    /**
     * 查询银行卡详细信息
     * @author 王海东
     * @date
     * @return void
     * @throws \Exception
     */
    public function findBank()
    {
        if (is_null(UID)) {
            rj(2, '登录失效，请重新登录');
        }

        $in = $this->I([
            [
                "id|银行卡id",
                null,
                "d",
                "require",
            ],
        ]);

        $b = new Bankinfo();

        $data = $b->find($in['id']);

        rjd($data);
    }

    /**
     * 删除银行卡
     * @author 王海东
     * @date
     * @return void
     * @throws \Exception
     */
    public function deleteBank()
    {
        if (is_null(UID)) {
            rj(2, '登录失效，请重新登录');
        }

        $in = $this->I([
            [
                "id|银行卡id",
                null,
                "d",
                "require",
            ],
        ]);

        $b = new Bankinfo();

        if (!$b->checkExits(1, $in['id'])) {
            rj(1, '删除失败，没有查到此卡');
        }

        if (!$b->delete($in['id'])) {
            rj(1, '删除失败');
        }

        rj();
    }

    /**
     * 修改银行卡
     * @author 王海东
     * @date
     * @return void
     * @throws \Exception
     */
    public function editBank()
    {
        $in = $this->I([
            [
                "id|银行卡id",
                null,
                "d",
                "require",
            ],
            [
                "bankname|银行名称",
                null,
                "s",
                "",
            ],
            [
                "bank_card_num|银行卡号",
                null,
                "d",
                "number",
            ],
            [
                "bank_branch|支行名称",
                null,
                "s",
                "",
            ],
            [
                "busername|持卡人",
                null,
                "s",
                "",
            ],
            [
                "card|身份证号",
                null,
                "s",
                "idCard",
            ],
            [
                "mobile|银行预留手机号",
                null,
                "s",
                "mobile",
            ],
            [
                "area|开户区域",
                null,
                "s",
            ],
        ]);

        if (is_null(UID)) {
            rj(2, '登录失效，请重新登录');
        }

        $b = new Bankinfo();

        if (!$b->checkExits(1, $in['id'])) {
            rj(1, '修改失败，系统未查到此卡');
        }

        if (!$b->update($in['id'], $in)) {
            rj(1, '修改失败');
        }

        rj();
    }

    /**
     * 实名认证
     * @author 王海东
     * @date
     * @return void
     * @throws \Exception
     */
    public function addUserReal()
    {
        if (is_null(UID)) {
            rj(2, '登录失效，请重新登录');
        }

        $in = $this->I([
            [
                "name|姓名",
                null,
                "s",
                "require",
            ],
            [
                "id_num|身份证号",
                null,
                "s",
                "require|idCard",
            ],
        ]);


        $ur = new UserReal();

        $info = $ur->find(UID);

        $res = false;

        if ($info) {
            if ($info['status'] == 1) {
                rj(1, '实名认证审核中，请勿重复提交');
            } elseif ($info['status'] == 2) {
                rj(1, '您的实名认证已经通过，请勿重复提交');
            }

            //如果拒绝审核则重新提交
            if ($info['status'] == 3) {
                $update = [
                    'name'   => $in['name'],
                    'id_num' => $in['id_num'],
                    'status' => 1,
                ];

                $res = $ur->edit(UID, $update);
            }
        } else {
            $insert = [
                'user_id' => UID,
                'name'    => $in['name'],
                'id_num'  => $in['id_num'],
            ];

            $res = $ur->add($insert);
        }

        if (!$res) {
            rj(1, '实名认证提交失败');
        }

        rj();
    }

    /**
     * 查询实名认证信息
     * @author 王海东
     * @date
     * @return void
     * @throws \Exception
     */
    public function getUserReal()
    {
        if (is_null(UID)) {
            rj(2, '登录失效，请重新登录');
        }

        $ur   = new UserReal();
        $data = $ur->find(UID);

        rjd($data);
    }

    /**
     * todo: 有bug, 未实现
     * 查询下级推广用户
     * @author 王海东
     * @date
     * @return void
     * @throws \Exception
     */
    public function getChild()
    {
        if (is_null(UID)) {
            rj(2, '登录失效，请重新登录');
        }

        $u    = new UserHierarchy();
        $data = $u->getChild(UID);

        rjd($data);
    }
}